package bl.finance;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.List;
import po.AccountorPo;
import po.Po;
import po.SystemLogPo;
import blservice.finance.AccountorBLService;
import vo.AccountorVo;
import vo.Vo;
import dbservice.finance.AccountorDBService;
import dbservice.history.SystemLogDBService;

public class AccountorBL extends UnicastRemoteObject implements AccountorBLService{

	private static final long serialVersionUID = 6634768805866693284L;
	private AccountorDBService db;
	private SystemLogDBService log;

	public AccountorBL(AccountorDBService accountorDB,SystemLogDBService log) throws RemoteException{
      this.db=accountorDB;
      this.log=log;
	}

	@Override
	public Vo addAccountor(AccountorVo vo) throws RemoteException {
		Po result=db.add(V2P(vo));
		if(result.isSuccessed()){
			log.add(new SystemLogPo(vo.getOperator(), "添加账户", vo.get名称()));
		}
		return P2V(result);
	}

	@Override
	public Vo deleteAccountor(AccountorVo vo)
			throws RemoteException {
		Po result=db.delete(V2P(vo));
		if(result.isSuccessed()){
			log.add(new SystemLogPo(vo.getOperator(), "删除账户", vo.get名称()));
		}
		return P2V(result);
	}

	@Override
	public boolean setMoney(AccountorVo vo)
			throws RemoteException {
		Po result=db.update(V2P(vo));
		return result.isSuccessed();
	}

	@Override
	public List<AccountorVo> getAll()
			throws RemoteException {
		List<AccountorVo> list=new ArrayList<AccountorVo>();
		List<AccountorPo> result=db.getAll();
		for(AccountorPo po:result){
			list.add(P2V(po));
		}
		return list;
	}
	
	private Vo P2V(Po po){
		AccountorVo vo=new AccountorVo();
		if(po.isSuccessed()){
			vo.successed();
		}else{
			vo.failed(po.getFailMessage());
		}
		return vo;
	}
	
	private AccountorVo P2V(AccountorPo po){
		AccountorVo vo=new AccountorVo();
		if(po.isSuccessed()){
			vo.set名称(po.get名称());
			vo.set金额(po.get金额());
			vo.successed();
		}else{
			vo.failed(po.getFailMessage());
		}
		return vo;
	}
	
	private AccountorPo V2P(AccountorVo vo){
		AccountorPo po=new AccountorPo();
		po.set名称(vo.get名称());
		po.set金额(vo.get金额());
		return po;
	}

	@Override
	public Vo updateAccountor(AccountorVo oldvo, AccountorVo newvo)
			throws RemoteException {
		Po result=db.rename(V2P(oldvo),V2P(newvo));
		if(result.isSuccessed()){
			log.add(new SystemLogPo(oldvo.getOperator(), "修改账户", oldvo.get名称()+"->"+newvo.get名称()));
		}
		return P2V(result);
	}
	
}

